<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="layout/base :: head">
</head>
<body>
    <div th:replace="layout/base :: nav"></div>

    <main class="container my-4">
        <h2><i class="bi bi-bicycle"></i> 运动记录</h2>
        <p>这里是运动记录管理页面。</p>
        
        <!-- 添加运动记录表单 -->
        <div class="card mb-4">
            <div class="card-header">
                <h3>添加运动记录</h3>
            </div>
            <div class="card-body">
                <form id="exerciseForm">
                    <div class="mb-3">
                        <label for="exerciseType" class="form-label">运动类型</label>
                        <input type="text" class="form-control" id="exerciseType" name="exerciseType" required>
                    </div>
                    <div class="mb-3">
                        <label for="duration" class="form-label">运动时长（分钟）</label>
                        <input type="number" class="form-control" id="duration" name="duration" required>
                    </div>
                    <div class="mb-3">
                        <label for="caloriesBurned" class="form-label">消耗卡路里</label>
                        <input type="number" class="form-control" id="caloriesBurned" name="caloriesBurned" required>
                    </div>
                    <div class="mb-3">
                        <label for="recordDate" class="form-label">记录日期</label>
                        <input type="date" class="form-control" id="recordDate" name="recordDate" required>
                    </div>
                    <div class="mb-3">
                        <label for="userId" class="form-label">用户ID</label>
                        <input type="number" class="form-control" id="userId" name="userId" required>
                    </div>
                    <button type="submit" class="btn btn-primary">提交</button>
                </form>
            </div>
        </div>

        <!-- 运动记录表格 -->
        <div class="card">
            <div class="card-header">
                <h3>运动记录列表</h3>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>运动类型</th>
                                <th>运动时长（分钟）</th>
                                <th>消耗卡路里</th>
                                <th>记录日期</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="exerciseTableBody">
                            <!-- 数据将通过 JavaScript 动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <div th:replace="layout/base :: footer"></div>
    <div th:replace="layout/base :: scripts"></div>

    <script>
        let editingId = null;

        // 加载运动记录数据
        function loadExerciseRecords() {
            fetch('/api/exerciserecords')
                .then(response => response.json())
                .then(data => {
                    const tableBody = document.getElementById('exerciseTableBody');
                    tableBody.innerHTML = '';
                    data.forEach(record => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${record.id}</td>
                            <td>${record.exerciseType}</td>
                            <td>${record.duration}</td>
                            <td>${record.caloriesBurned}</td>
                            <td>${record.recordDate}</td>
                            <td>
                                <button class="btn btn-sm btn-warning" onclick="editExerciseRecord(${record.id})">编辑</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteExerciseRecord(${record.id})">删除</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                })
                .catch(error => console.error('Error loading exercise records:', error));
        }

        // 提交运动记录表单
        document.getElementById('exerciseForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const formData = new FormData(this);
            const exerciseRecord = {
                exerciseType: formData.get('exerciseType'),
                duration: parseInt(formData.get('duration')),
                caloriesBurned: parseFloat(formData.get('caloriesBurned')),
                recordDate: formData.get('recordDate'),
                user: { id: parseInt(formData.get('userId')) }
            };

            if (editingId) {
                // 编辑模式
                fetch(`/api/exerciserecords/${editingId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(exerciseRecord)
                })
                .then(response => response.json())
                .then(data => {
                    alert('运动记录修改成功！');
                    loadExerciseRecords();
                    this.reset();
                    editingId = null;
                    document.querySelector('#exerciseForm button[type="submit"]').textContent = '提交';
                })
                .catch(error => console.error('Error updating exercise record:', error));
            } else {
                // 新增模式
                fetch('/api/exerciserecords', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(exerciseRecord)
                })
                .then(response => response.json())
                .then(data => {
                    alert('运动记录添加成功！');
                    loadExerciseRecords();
                    this.reset();
                })
                .catch(error => console.error('Error adding exercise record:', error));
            }
        });

        // 编辑运动记录
        function editExerciseRecord(id) {
            fetch(`/api/exerciserecords/${id}`)
                .then(response => response.json())
                .then(record => {
                    document.getElementById('exerciseType').value = record.exerciseType;
                    document.getElementById('duration').value = record.duration;
                    document.getElementById('caloriesBurned').value = record.caloriesBurned;
                    document.getElementById('recordDate').value = record.recordDate;
                    document.getElementById('userId').value = record.user ? record.user.id : '';
                    editingId = id;
                    document.querySelector('#exerciseForm button[type="submit"]').textContent = '保存修改';
                })
                .catch(error => console.error('Error loading exercise record for edit:', error));
        }

        // 删除运动记录
        function deleteExerciseRecord(id) {
            if (confirm('确定要删除这条运动记录吗？')) {
                fetch(`/api/exerciserecords/${id}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (response.ok) {
                        alert('运动记录删除成功！');
                        loadExerciseRecords();
                        // 如果正在编辑被删除的记录，重置表单
                        if (editingId === id) {
                            document.getElementById('exerciseForm').reset();
                            editingId = null;
                            document.querySelector('#exerciseForm button[type="submit"]').textContent = '提交';
                        }
                    }
                })
                .catch(error => console.error('Error deleting exercise record:', error));
            }
        }

        // 页面加载时加载运动记录
        document.addEventListener('DOMContentLoaded', loadExerciseRecords);
    </script>
</body>
</html> 